package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static String KEY_PREFIX="verify:code:phone";

    @Autowired
    private UserMapper userMapper;

    public Boolean checkUserData(String data, Integer type) {
        User user = new User();

        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
                default:
                    throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        int count = userMapper.selectCount(user);

        return count==0;
    }



    public void sendCode(String phone) {

        //对手机号码的校验
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }

        //生成随机验证码
        String code  = RandomStringUtils.randomNumeric(6);

        //把验证码保存到Redis中
        redisTemplate.opsForValue().set(KEY_PREFIX + phone,code,5, TimeUnit.MINUTES);


        //发送RabbitMQ消息到ly-sms

        HashMap<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public void register(User user, String code) {

        //验证码校验
        //从Redis中取出验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,cacheCode)){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //写入数据
        int count = userMapper.insertSelective(user);
        if (count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }



    public UserDTO query(String username, String password) {

        //根据用户名查询用户
        User user = new User();
        user.setUsername(username);
        User result = userMapper.selectOne(user);
        if (result==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //获取密码，对比密码是否正确
        if (!passwordEncoder.matches(password, result.getPassword())){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //转化DTO
        return BeanHelper.copyProperties(result,UserDTO.class);

    }
}